'use strict';

const { Service } = require('egg');
const Expense = require('../model/expense');
const Budget = require('../model/budget');

class ExpenseService extends Service {
    toDTO(expense) {
        return {
            id: expense.id,
            budgetId: expense.budget_id,
            userId: expense.user_id,
            category: expense.category,
            amount: Number(expense.amount || 0),
            currency: expense.currency,
            date: expense.date,
            description: expense.description || '',
        };
    }

    async list(userId, query = {}) {
        const { budgetId, startDate, endDate, category } = query;
        const where = { user_id: userId };
        if (budgetId) where.budget_id = Number(budgetId);
        if (category) where.category = category;
        // 日期范围
        if (startDate && endDate) {
            where.date = { $between: [startDate, endDate] };
        }
        const expenses = await Expense.findAll({ where, order: [['date', 'ASC']] });
        return { success: true, data: expenses.map(e => this.toDTO(e)) };
    }

    async create(userId, payload) {
        const { budgetId, category, amount, date, description, currency } = payload;
        if (!budgetId) return { success: false, message: 'budgetId必填' };
        const budget = await Budget.findOne({ where: { id: budgetId, user_id: userId } });
        if (!budget) return { success: false, message: '预算不存在或无权限' };

        const exp = await Expense.create({
            budget_id: budgetId,
            user_id: userId,
            category,
            amount: amount || 0,
            currency: currency || 'CNY',
            date,
            description,
        });
        return { success: true, data: this.toDTO(exp) };
    }

    async update(id, userId, payload) {
        const exp = await Expense.findOne({ where: { id, user_id: userId } });
        if (!exp) return { success: false, message: '支出记录不存在或无权限' };

        const { category, amount, date, description, currency } = payload;
        const updateFields = {};
        if (category !== undefined) updateFields.category = category;
        if (amount !== undefined) updateFields.amount = amount;
        if (currency !== undefined) updateFields.currency = currency;
        if (date !== undefined) updateFields.date = date;
        if (description !== undefined) updateFields.description = description;

        await Expense.update(updateFields, { where: { id } });
        const updated = await Expense.findByPk(id);
        return { success: true, data: this.toDTO(updated) };
    }

    async destroy(id, userId) {
        const exp = await Expense.findOne({ where: { id, user_id: userId } });
        if (!exp) return { success: false, message: '支出记录不存在或无权限' };
        await Expense.destroy({ where: { id } });
        return { success: true };
    }
}

module.exports = ExpenseService;